package common.utils;

import admin.dao.DomeDao;
import admin.entity.Dome;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class HibernateUtil {
    private boolean fleat = false;
    private Configuration cf = null;
    private Session session =null;
    private org.hibernate.Transaction Transaction =null;
    private int consulting = 1;
    private int suggest = 1;
    private int complaints = 1;

    //获取Session
    /**
     * 创建工厂会话
     * @return Session	工厂会话*/
    public  Session getSession(){
        cf =new Configuration();
        cf.configure();
        @SuppressWarnings("deprecation")
        // 创建服务注册对象
                ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cf.getProperties())
                .buildServiceRegistry();
        // 创建会话工厂对象
        SessionFactory sessionFactory = cf.buildSessionFactory(serviceRegistry);
        session = sessionFactory.openSession();
        //进行事务处理
        Transaction = session.beginTransaction();
        return session;
    }
    /**
     * @Author 谭永超 [www.tanyongchao.tk]
     * @Date 2018/7/30 02:04
     * @Description 添加
    */
    public static int add(Dome dome){
        HibernateUtil h = new HibernateUtil();
        h.getSession().save(dome);
        allclose(h);
        return 0;
    }

    /**
     * @Author 谭永超 [www.tanyongchao.tk]
     * @Date 2018/7/30 02:05
     * @Description 分页查询
    */
    public static List<Dome> getSelect(int page,String hql){
        HibernateUtil h = new HibernateUtil();
        List<Dome> list;
        Query query = h.getSession().createQuery(hql);
        query.setFirstResult(page * 9);//设置起始行数，从0开始计数
        query.setMaxResults(9);//设置返回的行数
        list = query.list();
        allclose(h);
        return list;
    }
    private static void allclose( HibernateUtil hibernateUtil){
        //提交事务
        hibernateUtil.Transaction.commit();
        //关闭会话
        hibernateUtil.session.close();

    }
    private HibernateUtil(){
    }
}
